package com.mmt.mapper;

import java.util.List;

import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;

import com.mmt.po.Message;
import com.mmt.po.User;

@Mapper
public interface ConversationMapper {
	@Select("SELECT \r\n"
    		+ "    u.*, \r\n"
    		+ "    cm.conversation_id,\r\n"
    		+ "    last_msg.content AS content,\r\n"
    		+ "    last_msg.created_at AS msg_created_at\r\n"
    		+ "FROM users u\r\n"
    		+ "JOIN conversation_members cm ON u.id = cm.user_id\r\n"
    		+ "JOIN (\r\n"
    		+ "    SELECT \r\n"
    		+ "        m1.conversation_id,\r\n"
    		+ "        m1.content,\r\n"
    		+ "        m1.created_at\r\n"
    		+ "    FROM messages m1\r\n"
    		+ "    WHERE m1.id = (\r\n"
    		+ "        SELECT MAX(m2.id) \r\n"
    		+ "        FROM messages m2 \r\n"
    		+ "        WHERE m2.conversation_id = m1.conversation_id\r\n"
    		+ "    )\r\n"
    		+ ") last_msg ON cm.conversation_id = last_msg.conversation_id\r\n"
    		+ "WHERE cm.conversation_id IN (\r\n"
    		+ "    SELECT conversation_id\r\n"
    		+ "    FROM conversation_members\r\n"
    		+ "    WHERE user_id = #{userId}  -- Current user ID\r\n"
    		+ ") \r\n"
    		+ "AND u.id != #{userId}  -- Exclude current user\r\n"
    		+ "ORDER BY last_msg.created_at DESC;")
	@Results({
        @Result(column = "msg_created_at", property = "created_at"),  // 映射
    })
	public	List<User> listContactByUserId(Integer userId);
	
	@Select("SELECT * FROM messages Where conversation_id = #{conversation_id};")
	@Results({
        @Result(column = "sender_id", property = "Id"),  // 映射
    })
	public List<Message> listMessageByConversationId(Integer conversation_id) ;
	
	@Insert("insert into messages values(null,#{conversation_id},#{id},#{content},default,null,null,default,default)")
	public int saveMessage(Message message) ;
}
 